package com.gitee.feizns.quickstart.spring.mqtt.spring.boot.autoconfigure;

import com.gitee.feizns.quickstart.mqtt.MqttConnection;
import com.gitee.feizns.quickstart.spring.mqtt.spring.boot.autoconfigure.event.MqttMessageArrivedEvent;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * MQTT 自动配置
 * @author feizns
 * @since 2024/6/23
 */
@Getter
@AutoConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(QuickstartMqttProperties.class)
public class QuickstartMqttAutoConfiguration {

    /**
     * 性能
     */
    private final QuickstartMqttProperties properties;

    /**
     * 事件发布者
     */
    private final ApplicationEventPublisher eventPublisher;

    /**
     * 快速入门 MQTT 实用程序
     * @param mqttCallbacks MQTT 回调
     * @return {@link MqttConnection}
     * @throws MqttException MQTT 异常
     */
    @Bean
    public MqttConnection mqttConnection(Collection<MqttCallback> mqttCallbacks) throws MqttException {
        MqttConnection connection = new MqttConnection(properties.getHost(), properties.getUsername(), properties.getPassword());
        mqttCallbacks.forEach(connection::register);
        if ( StringUtils.hasText(properties.getTopic()) )
            connection.sub(properties.getTopic(), properties.getQos());
        return connection;
    }

    /**
     * 事件 MQTT 回调
     * @return {@link MqttCallback }
     */
    public MqttCallback eventMqttCallback() {
        return new MqttCallback() {;
            @Override
            public void connectionLost(Throwable cause) {
                // 连接丢失
            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                eventPublisher.publishEvent(new MqttMessageArrivedEvent(topic, mqttMessage));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        };
    }

}
